#include "filemanager.h"

#include <QCoreApplication>
#include <QTextCodec>

FileManager::FileManager()
{
}

FileManager& FileManager::Instance()
{
    static FileManager instance;
    return instance;
}
FileManager::~FileManager()
{

}
void FileManager::CreateDir(QString path)
{
    QDir targetDir(path);
    if(!targetDir.exists())
    {
        if(!targetDir.mkdir(targetDir.absolutePath()))
        {
            qDebug()<<"Failed to create file folder!";
        }
    }
}

void FileManager::DeleteDir(QString path)
{
    QDir qDir(path);
    if(qDir.exists())
    {
        qDir.rmdir(qDir.absolutePath());
    }
    else
        qDebug()<<"Floder doesn's exists, delete failed:"<<path;
}

void FileManager::CopyDir(QString des, QString src)
{
    //将src下的所有子文件夹和文件拷贝一份到des中
    QDir srcDir(des);
    QDir desDir(src);
    // 获取所有文件和子目录
    QFileInfoList fileList = desDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
    // 遍历所有文件和子目录
    for (int i = 0; i < fileList.size(); i++)
    {
        QFileInfo fileInfo = fileList.at(i);
        QString filePath = fileInfo.filePath();
        QString fileName = fileInfo.fileName();
        // 如果是文件，复制到src路径下
        if (fileInfo.isFile())
        {
            QFile::copy(filePath, srcDir.filePath(fileName));
        }
        // 如果是子目录，递归调用Copy函数
        else if (fileInfo.isDir())
        {
            // 创建目录
            QDir newDir(srcDir);
            newDir.mkdir(fileName);
            // 递归调用Copy函数
            CopyDir(newDir.filePath(fileName),filePath);
        }
    }
}

bool FileManager::DeleteFile(QString filePath)
{
    QFileInfo fileInfo(filePath);
        if (fileInfo.exists()) {
            QFile file(filePath);
            if (!file.remove()) {
                qDebug() << "删除文件失败！";
                return false;
            }
        } else {
            qDebug() << "文件不存在！";
            return false;
        }
        return true;
}

void FileManager::CopyFile(QString src, QString des,bool justDir)
{
    QFile qFile(src);
    if(justDir)
    {
        QDir dir(src);
        des += "/" + dir.dirName();
    }
    QFile qFileDes(des);
    if(justDir && !qFileDes.exists())
    {
        QDir d;
        d.mkdir(des);
    }
    else if(!justDir)
    {
        QFileInfo info(des);
        QString path = info.path();
        QFile file(path);
        if(!file.exists())
        {
            QDir d;
            d.mkdir(path);
        }
    }
    if(qFile.exists() && !qFileDes.exists())
    {
        qFile.copy(des);
    }
    else
    {
        qDebug()<<"Source file doesn't exist or destination exist, copy failed.SRC:"<<src
               <<"  DES"<<des;
    }
    QDir dir(src);
}

void FileManager::MoveFile(QString src, QString des)
{
    QFile qFile(src);
    QFile qFileDes(des);
    if(qFile.exists() && !qFileDes.exists())
    {
        qFile.copy(des);
        qFile.remove();
    }
    else
        qDebug()<<"Source file doesn't exist or destination file has exist, move failed.SRC:"
               <<src<<"  DES:"<<des;
}

void FileManager::RenameFile(QString path, QString name)
{
    QFile qFile(path);
    if(qFile.exists())
        qFile.rename(name);
    else
        qDebug()<<"File doesn't exist, rename failed."<<path;
}

int FileManager::GetFileType(QString path)
{
    path.replace("\\","/");
    QString suffix = QFileInfo(path).suffix();
    int t = -1;
    if(suffix == "mp3" || suffix == "wav")
        t = FileManager::SOUND;
    else if(suffix == "mp4")
        t = FileManager::VIDEO;
    else if(suffix == "png" || suffix == "jpg" || suffix == "jpeg")
        t = FileManager::IMAGE;
    return t;
}

void FileManager::SaveData()
{
    JsonTranslator jt;
    QJsonObject* ob = jt.ToJson();
    if(!ob)
    {
        qDebug()<<__FILE__<<__LINE__<<"保存游戏数值失败";
    }
    Write(gameDataPath,jt.Json2Byte(ob));
    delete ob;
    ob = nullptr;
}

void FileManager::SetRootPath(QString path)
{
    this->rootPath = path;
}
QString FileManager::GetRootPath()
{
    return this->rootPath;
}

void FileManager::Write(QString filePath, QByteArray byteArray)
{
    QFileInfo fileInfo(filePath);
     QDir dir = fileInfo.absoluteDir();
     if(!dir.exists())
     {
         dir.mkpath(".");
     }
     QFile file(filePath);
     if(!file.open(QIODevice::WriteOnly))
     {
         qDebug() << "Open file error: " << file.errorString();
         return;
     }
     file.write(byteArray);
     file.close();
     qDebug() << "Write successfully!";
}

QJsonObject *FileManager::ReadJsonFile(const QString &path)
{
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "[FileManager::ReadJsonFile]  Failed to open file."<<path;
        return nullptr;
    }
    QTextStream in(&file);
    in.setCodec("UTF-8");
    QString jsonString = in.readAll();
    file.close();

   // 将json字符串转换为QJsonObject对象
   QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
   QJsonObject* jsonObj = new QJsonObject(jsonDoc.object());
   return jsonObj;
}
